package com.zjlab.georeceive.handler;

import com.zjlab.georeceive.GeoProcessor;
import com.zjlab.georeceive.bean.AreaBase;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author xue
 * @create 2022-11-07 16:15
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ChannelHandler.Sharable
public class GeoReceiveUdpHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private final GeoProcessor geoProcessor;

    private static final Integer FRAME_LENGTH = 107;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
        ByteBuf data = datagramPacket.content();
        int length = data.readableBytes();
        if (length == FRAME_LENGTH) {
            int stationId = data.getInt(62);
            int latitude = data.getInt(40);
            int longitude = data.getInt(44);
            int ldm = data.getShort(48);
            int sdm = data.getShort(50);
            AreaBase areaBase = new AreaBase(stationId, latitude, longitude, ldm, sdm);
            geoProcessor.receiveAreaBase(areaBase);
        }
    }

}
